<template>
  <RenderTableColumn v-bind="column" />
</template>

<script setup lang="tsx" name="TableColumn">
import type { Component } from "vue";
import { useSlots } from "vue";
import { ElTableColumn, ElTag } from "element-plus";
import { ColumnProps, RenderScope, HeaderRenderScope } from "../../type";
import { handleProp, handleRowAccordingToProp } from "@/utils";
import { ComType } from "@/components/Form/type";
import { useCom } from "@/components/Form";
import ColumnRender from "./ColumnRender.vue";
defineProps<{ column: ColumnProps }>();

const slots = useSlots();

// 渲染表格数据
const renderCellData = (item: ColumnProps, scope: RenderScope<any>) => {
  return handleRowAccordingToProp(scope.row, item.prop!);
};
const RenderTableColumn = (item: ColumnProps) => {
  return (
    <>
      {
        <ElTableColumn align={"left"} {...item}>
          {{
            default: (scope: RenderScope<any>) => {
              if (item._children) return item._children.map(child => RenderTableColumn(child));
              if (item.el) {
                let el: ComType | Component | undefined = item.el;
                if (typeof el === "string") {
                  const com = useCom(el);
                  if (!com) {
                    throw new Error("组件名" + el + "不存在");
                  }
                  el = com;
                }
                return <ColumnRender el={el} row={scope.row} column={item}></ColumnRender>;
              }
              if (item.render) return item.render(scope);
              if (slots[handleProp(item.prop!)]) return slots[handleProp(item.prop!)]!(scope);
              if (item.enum) {
                const value = handleRowAccordingToProp(scope.row, item.prop!);
                for (const element of item.enum) {
                  if (element.value === value) {
                    return (
                      <ElTag type={element.type} color={element.color}>
                        {element.label}
                      </ElTag>
                    );
                  }
                }
              }
              return renderCellData(item, scope);
            },
            header: (scope: HeaderRenderScope<any>) => {
              if (item.headerRender) return item.headerRender(scope);
              if (slots[`${handleProp(item.prop!)}Header`]) return slots[`${handleProp(item.prop!)}Header`]!(scope);
              return item.label;
            }
          }}
        </ElTableColumn>
      }
    </>
  );
};
</script>
